package com.hds.common.upload;

import com.hds.common.exception.RRException;
import com.hds.common.utils.R;
import com.hds.common.validator.Assert;
import com.hds.modules.sys.entity.config.UploadFileConfig;
import com.hds.modules.sys.entity.constant.ResCode;
import net.coobird.thumbnailator.Thumbnails;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.UUID;

/**
 * @Author guonan
 * @Email guonan@yewcn.com
 * @Description
 * @Date 2018/7/26 15:01
 */
public class UploadUtils {

    private static Logger logger = LoggerFactory.getLogger(UploadUtils.class);
    public static final String MARKER_LIBS="libs_";


    /**
     * 展示上传文件
     *
     * @param request
     * @param response
     * @param uploadFileConfig
     * @param imageName
     * @param width
     * @param height）
     */
    public static void getIcon(HttpServletRequest request,
                    HttpServletResponse response, UploadFileConfig uploadFileConfig,
                               String imageName, Integer width, Integer height){
        String prefix=null;
        try {
            prefix = imageName.substring(0,MARKER_LIBS.length());
        } catch (Exception e) {
            throw new RRException(e.getMessage());
        }
        Assert.isBlank(imageName, "图片名不能为空.");

        String fileName = null;
        if(imageName!=null && MARKER_LIBS.equals(prefix)) {
            fileName=uploadFileConfig.getFileLibraryStoragePath() + imageName;
        }else{

            int isexist = request.getRequestURI().indexOf("/app/file");
            if( isexist > 0){
                fileName=uploadFileConfig.getFrontFileStoragePath() + imageName;
            }else{
                fileName=uploadFileConfig.getFileStoragePath() + imageName;
            }
            //fileName=uploadFileConfig.getDomainFile() + imageName;
        }
        System.out.println("libs  fileName="+fileName);
        File file = new File(fileName);
        if(!file.exists())
        {
            throw new RRException("文件不存在");
        }

        try {
            BufferedImage im = ImageIO.read(file);
            /* 原始图像的宽度和高度  */
            int orinWidth = im.getWidth();
            int orinHeight = im.getHeight();

            FileInputStream inputStream = new FileInputStream(file); //原始文件的输入流
            byte[] data = new byte[(int)file.length()]; //原始文件的字节长度

            int length = inputStream.read(data);
            inputStream.close();


            Path path = Paths.get(fileName);
            String contentType = null;
            try {
                contentType = Files.probeContentType(path);
                response.setContentType(contentType);

            } catch (IOException e) {
                e.printStackTrace();
            }



            byte [] buf = null;
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            OutputStream stream = response.getOutputStream();

            if(width==null || width >= orinWidth || width<=0){
                width = orinWidth;
            }
            if(height==null || height >= orinHeight || height<=0){
                height = orinHeight;
            }

            Thumbnails.of(file).size(width,height).toOutputStream(outputStream);
            buf = outputStream.toByteArray();

            stream.write(buf);
            stream.flush();
            stream.close();
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 文件上传具体实现方法（单文件上传）
     *
     */
    public static R upload(HttpServletRequest request, Integer thumbWidth, Integer thumbHeight,
                              UploadFileConfig uploadFileConfig, MultipartFile file){

        if (!file.isEmpty()) {
            long maxSize=uploadFileConfig.getMaxSize();//文件允许上传的最大尺寸（5M）
            long currFileSize = file.getSize() / 1024;//上传文件的大小(K)

            if(currFileSize > maxSize){
                return R.error(ResCode.UPLOAD_FILE_MAX_SIZE, ResCode.UPLOAD_FILE_MAX_SIZE_DESC+maxSize+"KB");
            }

            String fileName="",thumbName="",finalName="";
            //String currDate = DateUtils.format(new Date(), "yyyyMMdd");
            try {
                fileName = file.getOriginalFilename();
                if(UploadUtils.isSupportCurrentSuffix(fileName, uploadFileConfig.getSuffixs())){

                    //如果是excel文件则不重命名
                    String suff=fileName.substring(fileName.lastIndexOf("."), fileName.length());
                    if(suff.indexOf("xlsx")>0 || suff.indexOf("xls")>0){
                        finalName = fileName;
                    }else{
                        //生成uuid
                        finalName = UUID.randomUUID().toString().replaceAll("-", "") + suff;
                    }
                    logger.info("finalName:{}",finalName);

                }else{
                    return R.error(ResCode.UPLOAD_FILE_SUFFIX_IS_SUPPORT, ResCode.UPLOAD_FILE_SUFFIX_IS_SUPPORT_DESC);
                }

//                String filePath = request.getServletContext().getRealPath("storage/");
////                		+ currDate + "/";
//            	String filePath = "E:/ABB/" + DateUtils.format(new Date(), "yyyyMMdd") + "/";

                String filePath = null;
                int isexist = request.getRequestURI().indexOf("/app/file/upload");
                System.out.println("isexist:"+isexist);
                if( isexist > 0){
                    filePath = uploadFileConfig.getFrontFileStoragePath(); //前端上传文件的存储路径
                }else{
                    filePath = uploadFileConfig.getFileStoragePath(); //上传文件的存储路径
                }


//                String filePath = uploadFileConfig.getDomainFile(); //上传文件的存储路径URL

                //原文件上传
                try {
                    UploadUtils.uploadFile(file.getBytes(), filePath, finalName);
                }catch(Exception e){
                    throw new RRException("文件上传失败,原因：" + e.getStackTrace());
                }
                //生成缩略图
                thumbName = UploadUtils.createThumbImage(file, thumbWidth, thumbHeight, filePath , finalName);

            } catch (FileNotFoundException e) {
                e.printStackTrace();
                throw new RRException("上传失败," + e.getMessage());
            } catch (IOException e) {
                e.printStackTrace();
                throw new RRException("上传失败," + e.getMessage());
            }catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            R r = R.ok("上传成功").put("fileName", finalName);
            if(thumbName!=null && !"".equals(thumbName)){
                r.put("thumbName", thumbName);
            }
            return r;
        } else {
            return R.error(ResCode.UPLOAD_FILE_IS_NULL, ResCode.UPLOAD_FILE_IS_NULL_DESC);
        }

    }




    /**
     * 文件上传
     * @param file
     * @param filePath
     * @param fileName
     * @throws Exception
     */
    public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
        logger.info("【file dir：{}】:" , filePath);
        File targetFile = new File(filePath);
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }
        logger.info("【file Path：{}】:" , filePath+fileName);
        FileOutputStream out = new FileOutputStream(filePath+fileName);
        out.write(file);
        out.flush();
        out.close();
    }


    /**
     * 根据文件名后缀判断上传的文件格式
     * @param fileName
     * @return
     */
    public static boolean isSupportCurrentSuffix(String fileName, String[] suffixs){
        String currSuffix =fileName.substring(fileName.lastIndexOf(".")+1, fileName.length()); //后缀
        if(Arrays.asList(suffixs).contains(currSuffix) && fileName.lastIndexOf(".") > -1){
            System.out.println(fileName);
            return true;
        }
        return false;

    }


    /**
     * 生成缩略图
     * @param file
     * @param thumbWidth
     * @param thumbHeight
     * @param filePath（路径+名称）
     * @throws IOException
     */
    public static String createThumbImage(MultipartFile file, Integer thumbWidth, Integer thumbHeight, String filePath, String finalName) throws IOException {

        String thumbSuffix = finalName.substring(finalName.lastIndexOf("."), finalName.length());
        String pureThumbName = finalName.substring(0,finalName.lastIndexOf("."));
        String thumbName = pureThumbName + "_thumb" + thumbSuffix;

        BufferedImage image = ImageIO.read(file.getInputStream());
        if (image != null) {	//如果image=null 表示上传的不是图片格式
            int w = image.getWidth();	//获取图片宽度，单位px
            int h = image.getHeight();	//获取图片高度，单位px

            if(thumbWidth != null && thumbHeight != null ){
                if(thumbWidth != w){
                    ////缩略图的宽/高(不按比例，按照指定宽高缩放),如果上传的图片宽度和将要压缩的指定宽度相等，则返回原图，不进行压缩
                    Thumbnails.of(file.getInputStream()).size(thumbWidth,thumbHeight).keepAspectRatio(false).toFile(filePath + thumbName);
                    //Thumbnails.of(file.getInputStream()).forceSize(thumbWidth,thumbWidth).toFile(filePath + thumbName);
                }
            }
            return thumbName;
        }
        return null;
    }


}
